import sys, pygame
from settings import Settings
from ship import Ship


class Alien_Invasion:
    def __init__(self):
        "游戏初始化"
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption('Alien Invasion')
        #    初始化飞船
        self.ship = Ship(self)

    def run_game(self):
        "开始游戏的循环"
        while True:
            # 检查按键事件
            self._check_events()
            # 调用ship类的update方法
            self.ship.update()
            # 刷新屏幕
            self._update_screen()

    def _check_events(self):
        # 监听键盘和鼠标事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)

    def _check_keydown_events(self,event):
        # 按下响应
        if event.key == pygame.K_RIGHT:
            # 响应ship类中的标志位，使其自行移动
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True

    def _check_keyup_events(self,event):
        # 松开响应
        if event.key == pygame.K_RIGHT:
            # 响应ship类中的标志，使其停止移动
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False
        elif event.key == pygame.K_q:
            # 按Q键退出游戏
            sys.exit()

    def _update_screen(self):
        self.screen.fill(self.settings.bg_color)
        # 初始化飞船的位置
        self.ship.blitm()
        # 不断的刷新屏幕
        pygame.display.flip()


if __name__ == '__main__':
    ai = Alien_Invasion()
    ai.run_game()
